#include <REGX52.H>

#define MAX_STEPS 50

#define LED_PORT P2
#define INPUT_KEYS P1

sbit RECORD_BTN = P3^6;
sbit PLAY_BTN = P3^7;

unsigned char recorded_steps[MAX_STEPS];
unsigned char step_count = 0;
bit recording = 0;

void delay_ms(unsigned int ms)
{
    unsigned int i, j;
    for(i=0; i<ms; i++)
        for(j=0; j<123; j++);
}

void main()
{
    unsigned char i, key;
    bit btn_inc_pressed = 0, btn_dec_pressed = 0;
    
    while(1)
    {
        // 记录按键检测（带消抖）
        if(RECORD_BTN == 0 && !btn_inc_pressed)
        {
            delay_ms(10);
            if(RECORD_BTN == 0)
            {
                btn_inc_pressed = 1;
                recording = 1;
                step_count = 0;
                LED_PORT = 0x00;  // 全亮提示开始记录
                delay_ms(500);
                LED_PORT = 0xFF;
            }
        }
        else if(RECORD_BTN == 1)
        {
            btn_inc_pressed = 0;
        }

        if(PLAY_BTN == 0 && !btn_dec_pressed && step_count > 0)
        {
            delay_ms(10);
            if(PLAY_BTN == 0)
            {
                btn_dec_pressed = 1;
                recording = 0;
                
                // 播放循环
                while(1)
                {
                    for(i=0; i<step_count; i++)
                    {
                        LED_PORT = ~(1 << recorded_steps[i]);
                        delay_ms(500);
                        LED_PORT = 0xFF;
                        delay_ms(100);
                        
                        // 检测退出播放
                        if(RECORD_BTN == 0 || PLAY_BTN == 0)
                        {
                            delay_ms(10);
                            if(RECORD_BTN == 0 || PLAY_BTN == 0)
                            {
                                while(RECORD_BTN == 0 || PLAY_BTN == 0);
                                LED_PORT = 0xFF;
                                break;
                            }
                        }
                    }
                    if(RECORD_BTN == 0 || PLAY_BTN == 0) break;
                }
            }
        }
        else if(PLAY_BTN == 1)
        {
            btn_dec_pressed = 0;
        }

        // 记录模式下检测输入按键
        if(recording)
        {
            for(key=0; key<8; key++)
            {
                if((INPUT_KEYS & (1<<key)) == 0)
                {
                    delay_ms(10);
                    if((INPUT_KEYS & (1<<key)) == 0)
                    {
                        while((INPUT_KEYS & (1<<key)) == 0);
                        
                        if(step_count < MAX_STEPS)
                        {
                            recorded_steps[step_count++] = key;
                            LED_PORT = ~(1 << key);
                            delay_ms(300);
                            LED_PORT = 0xFF;
                        }
                        break;
                    }
                }
            }
        }
        
        delay_ms(10);
    }
}